﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain.Entity;
using Casamiel.Domain;
using Casamiel.Domain.Request.IC;
using Casamiel.Domain.Response;
using Enyim.Caching;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands
{
    /// <summary>
	/// 
	/// </summary>
    public sealed  class OrderCreateMemberCouponCommandHandler:BaseCommandHandler,IRequestHandler<OrderCreateMemberCouponCommand,BaseResult<string>>
    {
        private readonly IMemberCardRepository _memberCardRepository;
        private readonly IMemcachedClient _memcachedClient;
        private readonly string _memcachedPrex;
        private readonly IMemberCouponRecordRepository _memberCouponRecordRepository;
        private readonly IOrderBaseRepository _orderBaseRepository;
        private readonly IOrderGoodsRepository _orderGoodsRepository;
        private readonly List<ActivityInfo> _activityInfos;
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="memberRepository"></param>
        /// <param name="memberCouponRecordRepository"></param>
        /// <param name="netICService"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="settings"></param>
        /// <param name="memcachedClient"></param>
        ///<param name="orderBaseRepository"></param>
        ///<param name="orderGoodsRepository"></param>
        public OrderCreateMemberCouponCommandHandler(IMemberCardRepository  memberCardRepository, IMemberCouponRecordRepository  memberCouponRecordRepository, INetICService netICService,
            IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings, IMemcachedClient memcachedClient, IOrderBaseRepository orderBaseRepository
           ,IOptionsSnapshot<List<ActivityInfo>> optionsSnapshot, IOrderGoodsRepository orderGoodsRepository) : base(netICService, httpClientFactory, settings)

		{
            if (optionsSnapshot == null)
            {
                throw new ArgumentNullException(nameof(optionsSnapshot));
            }
            _memberCardRepository = memberCardRepository;
            _memberCouponRecordRepository = memberCouponRecordRepository;
			_memcachedClient = memcachedClient;
			_memcachedPrex = settings.Value.MemcachedPre;
            _orderBaseRepository = orderBaseRepository;
            _activityInfos = optionsSnapshot.Value;
            _orderGoodsRepository = orderGoodsRepository;
 

		}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<BaseResult<string>> Handle(OrderCreateMemberCouponCommand request, CancellationToken cancellationToken)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }
			if (this.Casasettings.ApiName != "hgspApi") {
				return new BaseResult<string>("", 0, "");
			}
			request.ActivityId = 7;
            var orderentity = await _orderBaseRepository.GetByOrderCodeAsync<ICasaMielSession>(request.OrderCode).ConfigureAwait(false);
            if (orderentity == null)
            {
                return new BaseResult<string>("", 9999, "");
            }
			 
            var cardentity = await _memberCardRepository.GetBindCardAsync<ICasaMielSession>(orderentity.Mobile).ConfigureAwait(false);
            if (cardentity == null)
            {
                return new BaseResult<string>("", 0, "");
            }
            var activityinfo = _activityInfos.Find(c => c.Id == request.ActivityId);
            if (activityinfo == null)
            {
                return new BaseResult<string>("", 999, "活动不存在");
            }
            
            if (!activityinfo.IsTest && activityinfo.Testers.Any(c=>c.phoneno==orderentity.Mobile))
            {
               
                if (activityinfo.BeginTime > DateTime.Now)
                {
                    
                    return new BaseResult<string>("", -31, "尚未开始");
                }
                if (activityinfo.EndTime < DateTime.Now)
                {
                    return new BaseResult<string>("", -32, "活动结束");
                }
                if (!activityinfo.Enable)
                {
                    return new BaseResult<string>("", -36, "活动已关闭");
                }
            }
          

            var coupon = new MemberCouponRecord { CardNO = cardentity.CardNO, Mobile = cardentity.Mobile, ActivityId = request.ActivityId, Status = 1, CreateTime = DateTime.Now,OrderCode=request.OrderCode };
            var req = new AddTicketsReq { Cardno = cardentity.CardNO, Phoneno = cardentity.Mobile };
            req.Largesstickets = new List<Domain.Request.IC.Ticket>();
            foreach (var item in activityinfo.Tickets)
            {
                req.Largesstickets.Add(new Domain.Request.IC.Ticket { Ticketid = item.TicketId, Ticketnum = item.Count, Ticketprice = item.Price });
            }
            coupon.RequestInfo = JsonConvert.SerializeObject(req);
            var d = await NetICService.Icticketlargess(req).ConfigureAwait(false);
            if (d.code == 0)
            {
                var jjobj = JsonConvert.DeserializeObject<JObject>(d.content);
                coupon.Largessno = jjobj["largessno"].ToString();
                await _memberCouponRecordRepository.SaveAsync<ICasaMielSession>(coupon).ConfigureAwait(false);
            }
             
            return new BaseResult<string>("", 0, "");
        }
    }
}
